package com.banyechan.lingo_words.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.banyechan.lingo_words.entity.EnglishWord;
import com.banyechan.lingo_words.entity.R;
import com.banyechan.lingo_words.exception.BusinessException;
import com.banyechan.lingo_words.exception.BusinessExceptionEnum;
import com.banyechan.lingo_words.service.IEnglishWordService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;


@Slf4j
@RestController
@RequestMapping("/english")
public class EnglishWordController {


    @Autowired
    private IEnglishWordService englishWordService;


    @GetMapping("/random")
    public R<EnglishWord> getRandomWord(){
        Random random = new Random();
        int randomId = random.nextInt(200);
        log.info("randomId={}", randomId);
        LambdaQueryWrapper<EnglishWord> query = Wrappers.<EnglishWord>lambdaQuery();
        query.eq(EnglishWord::getId, randomId);
        return R.ok(englishWordService.getOne(query));
    }


    /**
     *  导入excle
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/importWords")
    public R<Boolean> importWords(@RequestParam("file") MultipartFile file){
        log.info("导入单词excle，文件名：{}", file.getName());
        List<EnglishWord> wordList = null;
        try {
           wordList = analysisExcel(file);
        }catch (Exception e){
            log.info("解析单词excle 异常:{}",e);
        }
        if(wordList == null || wordList.size() < 1){
            throw new BusinessException(BusinessExceptionEnum.EXCEL_PARSING_NULL);
        }
        for(EnglishWord temWord : wordList){
            LambdaQueryWrapper<EnglishWord> query = Wrappers.<EnglishWord>lambdaQuery();
            query.eq(StringUtils.isNotBlank(temWord.getWord()), EnglishWord::getWord, temWord.getWord());

            List<EnglishWord> wordDBList = englishWordService.list(query);
            if(wordDBList != null && wordDBList.size() > 0){
                log.info("{}已存在", temWord.getWord());
                continue;
            }

            temWord.setCreateTime(new Date());
            temWord.setUpdateTime(new Date());
            englishWordService.save(temWord);
        }

        return R.ok(true);
    }

    public List<EnglishWord> analysisExcel(MultipartFile file) throws IOException {
        List<EnglishWord> wordList = null;
        // 解析文件,文件内容为空直接返回失败
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        reader.addHeaderAlias("单词", "word");
        reader.addHeaderAlias("国际音标", "ipa");
        reader.addHeaderAlias("美式音标", "sampa");
        reader.addHeaderAlias("中文", "chineseMean");
        List<Object> tableNames = reader.readRow(0);
        log.info("本次解析数据表头为：【{}】", JSONUtil.toJsonStr(tableNames));
        if (!tableNames.stream().anyMatch(name -> "单词".equals(name))) {
            throw new BusinessException(BusinessExceptionEnum.EXCEL_PARSING_TITLE_NAME, "单词");
        }
        if(!tableNames.stream().anyMatch(name -> "国际音标".equals(name))){
            throw new BusinessException(BusinessExceptionEnum.EXCEL_PARSING_TITLE_NAME, "国际音标");
        }
        if(!tableNames.stream().anyMatch(name -> "美式音标".equals(name))){
            throw new BusinessException(BusinessExceptionEnum.EXCEL_PARSING_TITLE_NAME, "美式音标");
        }
        if (!tableNames.stream().anyMatch(name -> "中文".equals(name))) {
            throw new BusinessException(BusinessExceptionEnum.EXCEL_PARSING_TITLE_NAME, "中文");
        }
        wordList = reader.readAll(EnglishWord.class);
        if(CollectionUtil.isEmpty(wordList)){
            throw new BusinessException(BusinessExceptionEnum.EXCEL_PARSING_NULL);
        }

        return wordList;
    }

}
